package com.szh.zx.javacorecorret.chap3.two;

import java.util.concurrent.Phaser;
// 章节 3.3
// 从结果来看，线程C 中途退出了比赛，导致 后面的比赛不能正常继续，这样的情况非常糟糕
public class PhaserTest2 {
	public static void main(String[] args) {
		Phaser phaser = new Phaser(3);
		PrintTool2.phaser = phaser;
		ThreadE threadA = new ThreadE(phaser);
		threadA.setName("A");
		threadA.start();

		ThreadF threadB = new ThreadF(phaser);
		threadB.setName("B");
		threadB.start();

		ThreadG threadC = new ThreadG(phaser);
		threadC.setName("C");
		threadC.start();
		System.out.println("主线程结束");
	}
}
// todo 章节 3.3
class PrintTool2{
	public static Phaser phaser;
	public static void methodA(){
		System.out.println(Thread.currentThread().getName()+" A1 begin ="+System.currentTimeMillis());
		// 到达 等待 促进。 这个方法的作用 是当线程到达 屏障，在此等待一段时间，等到条件满足后继续向下一个屏障继续执行
		phaser.arriveAndAwaitAdvance();
		System.out.println(Thread.currentThread().getName()+" A1 end ="+System.currentTimeMillis());

		System.out.println(Thread.currentThread().getName()+" A2 begin ="+System.currentTimeMillis());
		phaser.arriveAndAwaitAdvance();
		System.out.println(Thread.currentThread().getName()+" A2 end ="+System.currentTimeMillis());

	}

	public static void methodB(){
		try {
			System.out.println(Thread.currentThread().getName()+" A1 begin ="+System.currentTimeMillis());
			Thread.sleep(5000);
			phaser.arriveAndAwaitAdvance();
			System.out.println(Thread.currentThread().getName()+" A1 end ="+System.currentTimeMillis());

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class ThreadG extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTool2.methodB();
	}

	public ThreadG(Phaser phaser) {
		this.phaser = phaser;
	}

}
class ThreadF extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTool2.methodA();
	}

	public ThreadF(Phaser phaser) {
		this.phaser = phaser;
	}

}
class ThreadE extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTool2.methodA();
	}

	public ThreadE(Phaser phaser) {
		this.phaser = phaser;
	}

}
